def count():
    fs = []
    for i in range(1, 4):
        def f():
            return i * i

        fs.append(f)
    return fs

# 返回闭包时牢记一点：返回函数不要引用任何循环变量，或者后续会发生变化的变量。
f1, f2, f3 = count()

print(f1())
print(f2())
print(f3())

# [1,5)
for i in range(1, 5):
    print("range", i)


def count():
    def f(j):
        def g():
            return j * j

        return g

    fs = []
    for i in range(1, 4):
        fs.append(f(i))  # f(i)立刻被执行，因此i的当前值被传入f()
    return fs


fns = count()
print(fns)
for fn in fns:
    print(fn())

"""
def inc():
    x = 0

    def fn():
        # 仅读取x的值:
        return x + 1

    return fn


f = inc()
print(f())  # 1
print(f())  # 1

"""


def inc():
    x = 0
    def fn():
        # 使用闭包时，对外层变量赋值前，需要先使用nonlocal声明该变量不是当前函数的局部变量。
        # nonlocal x
        x = x + 1
        return x
    return fn

f = inc()
print(f()) # 1
print(f()) # 2